{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6c7d80a5",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "# Synthetic Regression Data\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b9773b7e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:11.561594Z",
     "iopub.status.busy": "2023-08-18T19:36:11.560983Z",
     "iopub.status.idle": "2023-08-18T19:36:15.344149Z",
     "shell.execute_reply": "2023-08-18T19:36:15.342706Z"
    },
    "origin_pos": 3,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import random\n",
    "import torch\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb2d5d12",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "$$\\mathbf{y}= \\mathbf{X} \\mathbf{w} + b + \\boldsymbol{\\epsilon}$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "38a83404",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:15.362285Z",
     "iopub.status.busy": "2023-08-18T19:36:15.361503Z",
     "iopub.status.idle": "2023-08-18T19:36:15.390526Z",
     "shell.execute_reply": "2023-08-18T19:36:15.389339Z"
    },
    "origin_pos": 9,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class SyntheticRegressionData(d2l.DataModule):  \n",
    "    \"\"\"Synthetic data for linear regression.\"\"\"\n",
    "    def __init__(self, w, b, noise=0.01, num_train=1000, num_val=1000,\n",
    "                 batch_size=32):\n",
    "        super().__init__()\n",
    "        self.save_hyperparameters()\n",
    "        n = num_train + num_val\n",
    "        self.X = torch.randn(n, len(w))\n",
    "        noise = torch.randn(n, 1) * noise\n",
    "        self.y = torch.matmul(self.X, w.reshape((-1, 1))) + b + noise\n",
    "\n",
    "data = SyntheticRegressionData(w=torch.tensor([2, -3.4]), b=4.2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "694561f1",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "Each row in `features` consists of a vector in $\\mathbb{R}^2$ and each row in `labels` is a scalar"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "43e267cb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:15.395708Z",
     "iopub.status.busy": "2023-08-18T19:36:15.394509Z",
     "iopub.status.idle": "2023-08-18T19:36:15.405078Z",
     "shell.execute_reply": "2023-08-18T19:36:15.402629Z"
    },
    "origin_pos": 11,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "features: tensor([0.9026, 1.0264]) \n",
      "label: tensor([2.5148])\n"
     ]
    }
   ],
   "source": [
    "print('features:', data.X[0],'\\nlabel:', data.y[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83d0c554",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "Implement the `get_dataloader` method,\n",
    "takes a batch size, a matrix of features,\n",
    "and a vector of labels, and generates minibatches of size `batch_size`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d5af1472",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:15.424253Z",
     "iopub.status.busy": "2023-08-18T19:36:15.423639Z",
     "iopub.status.idle": "2023-08-18T19:36:15.430119Z",
     "shell.execute_reply": "2023-08-18T19:36:15.429099Z"
    },
    "origin_pos": 15,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "X shape: torch.Size([32, 2]) \n",
      "y shape: torch.Size([32, 1])\n"
     ]
    }
   ],
   "source": [
    "@d2l.add_to_class(SyntheticRegressionData)\n",
    "def get_dataloader(self, train):\n",
    "    if train:\n",
    "        indices = list(range(0, self.num_train))\n",
    "        random.shuffle(indices)\n",
    "    else:\n",
    "        indices = list(range(self.num_train, self.num_train+self.num_val))\n",
    "    for i in range(0, len(indices), self.batch_size):\n",
    "        batch_indices = torch.tensor(indices[i: i+self.batch_size])\n",
    "        yield self.X[batch_indices], self.y[batch_indices]\n",
    "\n",
    "X, y = next(iter(data.train_dataloader()))\n",
    "print('X shape:', X.shape, '\\ny shape:', y.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fab4cb3b",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "Call the existing API in a framework to load data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "2f5d57c3",
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "4"
    },
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:15.464003Z",
     "iopub.status.busy": "2023-08-18T19:36:15.462740Z",
     "iopub.status.idle": "2023-08-18T19:36:15.474793Z",
     "shell.execute_reply": "2023-08-18T19:36:15.473623Z"
    },
    "origin_pos": 21,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "X shape: torch.Size([32, 2]) \n",
      "y shape: torch.Size([32, 1])\n"
     ]
    }
   ],
   "source": [
    "@d2l.add_to_class(d2l.DataModule)  \n",
    "def get_tensorloader(self, tensors, train, indices=slice(0, None)):\n",
    "    tensors = tuple(a[indices] for a in tensors)\n",
    "    dataset = torch.utils.data.TensorDataset(*tensors)\n",
    "    return torch.utils.data.DataLoader(dataset, self.batch_size,\n",
    "                                       shuffle=train)\n",
    "\n",
    "@d2l.add_to_class(SyntheticRegressionData)  \n",
    "def get_dataloader(self, train):\n",
    "    i = slice(0, self.num_train) if train else slice(self.num_train, None)\n",
    "    return self.get_tensorloader((self.X, self.y), train, i)\n",
    "\n",
    "X, y = next(iter(data.train_dataloader()))\n",
    "print('X shape:', X.shape, '\\ny shape:', y.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "790cbdfb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:15.479797Z",
     "iopub.status.busy": "2023-08-18T19:36:15.478884Z",
     "iopub.status.idle": "2023-08-18T19:36:15.489245Z",
     "shell.execute_reply": "2023-08-18T19:36:15.488320Z"
    },
    "origin_pos": 23,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "32"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(data.train_dataloader())"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "language_info": {
   "name": "python"
  },
  "required_libs": [],
  "rise": {
   "autolaunch": true,
   "enable_chalkboard": true,
   "overlay": "<div class='my-top-right'><img height=80px src='http://d2l.ai/_static/logo-with-text.png'/></div><div class='my-top-left'></div>",
   "scroll": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}